//
//  UMPGraphView.m
//  UMPDemo
//
//  Created by Jonathan Diehl on 05.03.10.
//  Copyright 2010 RWTH. All rights reserved.
//

#import "UMPGraphView.h"

#import "UMPListener.h"
#import "UMPTouch.h"
#import "ump.h"


#define UMP_GRAPH_VIEW_QUEUEU_SIZE 100

#define BGCOLOR 0.0, 0.0, 0.0, 1.0
#define GRAPH_COLOR 1.0, 1.0, 1.0, 1.0


@implementation UMPGraphView

@synthesize umpListener;

// init
- (id)initWithFrame:(NSRect)frame;
{
	self = [super initWithFrame:frame];
	if (self != nil) {
		
		// init queue
		touchQueue = [[NSMutableArray alloc] initWithCapacity:UMP_GRAPH_VIEW_QUEUEU_SIZE];
		
		// start timer
		updateTimer = [[NSTimer alloc] initWithFireDate:[NSDate date] interval:1.0 target:self selector:@selector(update) userInfo:nil repeats:YES];
	}
	return self;
}

// cleanup
- (void)dealloc
{
	[updateTimer invalidate];
	[updateTimer release];
	[umpListener release];
	[touchQueue release];
	[super dealloc];
}


# pragma mark queue methods

- (void)addTouch:(UMPTouch *)touch;
{
	// trim queue
	if([touchQueue count] >= UMP_GRAPH_VIEW_QUEUEU_SIZE) {
		[touchQueue removeObjectAtIndex:0];
	}
	
	// add touches to queue
	[touchQueue addObject:touch];
	
	// redraw
	[self setNeedsDisplay:YES];
}


# pragma mark timer methods

// update display
- (void)update;
{
	[self setNeedsDisplay:YES];
}


# pragma mark drawing

// drawing
- (void)drawRect:(NSRect)rect;
{
	NSRect bounds = self.bounds;
	
	CGContextRef c = [[NSGraphicsContext currentContext] graphicsPort];
	
	// draw background
	CGContextSetRGBFillColor(c, BGCOLOR);
	CGContextFillRect(c, bounds);
	
	CGFloat dx = bounds.size.width / UMP_GRAPH_VIEW_QUEUEU_SIZE;
	CGFloat dy = bounds.size.height;
	
	// draw the touch graph
	NSBezierPath *path = [[NSBezierPath alloc] init];
	BOOL drawing = NO;
	UMPTouch *touch;
	NSUInteger i = 0;
	NSPoint p;
	for(touch in touchQueue) {
		p.x = dx * i++;
		p.y = dy * touch.pressure;
		if(!drawing) {
			[path moveToPoint:p];
			drawing = YES;
		} else {
			[path lineToPoint:p];
		}
	}

	CGContextSetRGBStrokeColor(c, GRAPH_COLOR);
	[path stroke];
	[path release];
}

@end
